var icon = new GIcon();
var red_icon = getIcon("red");//new GIcon();
var gray_icon = getIcon("gray");//new GIcon();
var green_icon = getIcon("green");//new GIcon();
var yellow_icon = getIcon("yellow");//new GIcon();
var white_icon = getIcon("white");// new GIcon();

var point_state;
var map;
var opts;
var marker;
var x0, y0, x, y;
var mtitle;

//停留时间
var stopover_time = 10;
var responsetext = "";
var elements;
var inited = false;
var intervalID = "-1";

var reTryCount = 0;

var mapType = "";
var uID = "";
var page = "";
function setUserID(userID){
	uID = userID;
}

//实例化的页面
function setPage(p){
	page = p;
}

//pw.print(jingDU + "," + weiDu + "," + shiJian + "," + vo.getSUDU()+","+userName+","
//+StringUtil.getStrByDate(new Date()) + "," + vo.getHANGXIANG()+ sys_time);

function getpoint() {
	var myAjax = new Ajax.Request("GetModifiedLocationInfo", {
		method :"post", //表单提交方式 
		parameters :"userID=" + uID+"&mapType="+mapType, //提交的表单数据
		onComplete : function(x) { //提交成功回调 
			//alert(x.responseText);
			responsetext = x.responseText;
			if(responsetext == null || responsetext == ""){
				document.write("没有位置数据！");
				return;
			}
			
			elements = responsetext.split(",");
			//changeLocationInfo();
			selectIconAndTitle();
			if(needReinit)
				initMarker();
			
			if (!inited)
				initMap();
			else
				darwLine();

			reTryCount = 0;
		},
		onError : function(x) { //提交失败回调
			//alert(x.statusText + "" + reTryCount);
			reTryCount = reTryCount + 1;
			if (reTryCount == 5) {
				//alert(x.statusText);
				if (intervalID != "-1")
					window.clearInterval(intervalID);
			}

		}
	});
}



function selectIconAndTitle() {
	//得到停留时间（单位秒）
/*	
	stopover_time = (new Date().getTime() - new Date(
			(elements[2].split("."))[0].replace(/-/g, "/")).getTime()) / 1000;
*/	
	//2---datatiem,8---heart_time,7-----sys_time,5---servertime
	stopover_time = getTimeDiff(elements[5], elements[2]);
	//stopover_time = getTimeDiff(elements[7], elements[2]);
	
//	alert(stopover_time);
	var heart_time = getTimeDiff(elements[5], elements[8]);
	var dingwei_time = getTimeDiff(elements[5], elements[7]);	
    if(dingwei_time < heart_time)
    	heart_time = dingwei_time;	
//    alert(heart_time);
	//alert(heart_time);
	point_state = getState(heart_time, elements[3], stopover_time);
    if(point_state == "green"){                     
        icon=green_icon;
        return;
       }
    if(point_state == "white"){
       icon=white_icon;
        return;
	}
	if (point_state == "gray"){ 
      icon=gray_icon;
      return;
   }
    
      if(point_state == "yellow"){
         // 黄灯，超速
         icon=yellow_icon;
        return;
      }   

       // 亮红,严重超速
       icon=red_icon;                    

              
	
	/*
	//用不同颜色的marker区分不同状态，
	if (stopover_time >= 300) {
		//30秒分钟变灰，设备静止
		icon = gray_icon;
		point_state = "gray";
		return;
	}
	if (elements[3] >= 120) {
		//红,严重超速
		icon = red_icon;
		point_state = "red";
		//             MM_controlSound('play', 'document.MM_120chaosu');
		return;
	}
	if (elements[3] >= 80) {
		//黄，超速
		icon = yellow_icon;
		point_state = "yellow";
		return;
	}

	//30分内有数据正常，行使中
	icon = green_icon;
	point_state = "green";
	*/
	return;
}

var initMTitle = "目标：。。。。。。。。<br>";
initMTitle += "状态：。。。。。<br>";
initMTitle += "里程：。。。。。<br>";
initMTitle += "信号：。。。。。。。。";
//建立标志函数
function create_title() {
	mtitle = "目标：" + elements[4] + " <br>";
	mtitle += "里程：" + formatDistance_(len) + "<br>";
	var showTime = elements[7].substring(0, 19);
	if(point_state == "white"){
		mtitle += "状态：离线<br>";//<br>时间："+elements[2];
		//mtitle += "方向：....<br>";
		mtitle += "定位：" + showTime;
		return;
	}
	if (point_state == "gray") {
		mtitle += "状态：静止<br>";//<br>时间："+elements[2];
		//mtitle += "方向：....<br>";
		mtitle += "定位：" + showTime;
		return;
	} 
 
		mtitle += "速度：" + elements[3] + "Km/h";//<br>时间："+elements[2];
		mtitle += "(" + getHangXiang(elements[6], elements[3]) + ")<br>";//+"("+elements[6]+"度)";
		
		mtitle += "定位：" + showTime;
		if(page=="index" && elements[3] != "0"){
			var dt = new Date().toLocaleString();			
			container.innerHTML += "<li>" + dt.substring(dt.indexOf("\ ")) + "   速度" + elements[3] + "公里/小时</li>";
		}
			return;
	
}

var needReinit = false;
function initMap() {
	map = new GMap2(document.getElementById("map"));
	//alert("aa");
	if(page=="index" || page == "" ){
		
	var mapControl = new GMapTypeControl();
    map.addControl(mapControl);
    map.removeMapType(G_SATELLITE_MAP);
	}
    map.addControl(new GLargeMapControl());
    //map.removeMapType(G_HYBRID_MAP); 
   

    
    GEvent.addListener(map, "maptypechanged", function(){

        //切换地图类型	
         //window.clearInterval(intervalID);
    	//alert("sdfsdfl;kj");
    	 mapType = (map.getCurrentMapType().getName() == "卫星") ?  "G_SATELLITE_MAP" : "";
         map.clearOverlays();  
         needReinit = true;//设置需要重新初始化                    
         len = 0;
      });
    
    if(page=="index" || page=="indexEng"){
    	GEvent.addListener(map, "click", function(){
    		tiyan();
          });
    	GEvent.addListener(map, "dblclick", function(){
    		tiyan();
          });    	
    }
      
    initMarker();
	
	//changeLocationInfo();
	inited = true;
}

var initZoom = 12;
function initMarker(){
	x = Number(elements[1]);
	y = Number(elements[0]);
	x0 = x;
	y0 = y;
	var center = new GLatLng(x, y);
	var point = center
	
/*	
	if(page=="index"){
		initZoom = 14;
	}
*/	
	if(map.getZoom() > initZoom)
		initZoom = map.getZoom();
	
	map.setCenter(center, initZoom);

	//构建标志1
	//       create_title(elements[4]);
	var point = new GLatLng(x, y);

	opts = {
		text :"<span id='markerText'><font size='1'>" + initMTitle
				+ "....</font></span>",
		icon :icon
	};
	marker = new PopupMarker(point, opts);
	//alert(icon);
	//marker.setImage(icon.image);
	
	//alert(point_state);
	map.addOverlay(marker);

	create_title();
	document.getElementById("markerText").innerHTML = "<span id='markerText'><font size='1'>"
			+ mtitle + "</font></span>";
	
	needReinit = false;
	
}



function changeLocationInfo() {
	var _spanOnLine = document.getElementById("spanOnLine");
	var script = document.createElement("script");
	script.src = "GetDataService?method=getLocationText&jing=" + elements[0]
			+ "&wei=" + elements[1];
	_spanOnLine.appendChild(script);
}

var runCount = 0;
var polylineArr = new Array();
var polyline;

function darwLine() {
	x = Number(elements[1]);
	y = Number(elements[0]);
	//	          create_title(elements[4]);
	var point = new GLatLng(x, y);

	if (Math.sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0)) > 0.0002) {
		var color = "#00FF00";
		if (point_state == "red")
			color = "#FF0000";
		else if (point_state == "yellow")
			color = "#FF00FF";

		polyline = new GPolyline( [ new GLatLng(x0, y0), new GLatLng(x, y), ],
				color, 5);

		//alert(runCount);
		//alert(x0 +"----" +y0 + "----" + x + "----" + y);
		//alert(len);
		len += new GLatLng(x0, y0).distanceFrom(new GLatLng(x, y));
		//alert(len);

		x0 = x;
		y0 = y;
		map.addOverlay(polyline);
		
		marker.setLatLng(point);
		
		//if(page=="index")
			//map.setCenter(point);

		polylineArr[runCount] = polyline;
		//	             alert(runCount + ":"+polylineArr[runCount])	
		runCount = runCount + 1;
	}
	create_title();
	document.getElementById("markerText").innerHTML = "<span id='markerText'><font size='1'>"
			+ mtitle + "</font></span>";
	//marker.setLatLng(point);
	marker.setImage(icon.image);
	
	//marker.hidePopup();	
   	marker.showPopup();	

}
